#include <stdio.h>

#include <mutex>

#include "xlcomm/net/event_loop.h"
#include "xlcomm/net/event_loop_thread.h"
using namespace xlcomm;

class Printer {
 public:
  Printer(net::EventLoop* loop, net::EventLoop* loop2)
      : loop_(loop), loop2_(loop2), num_(0) {
    loop_->RunAfter(1, std::bind(&Printer::Print1, this));
    loop2_->RunAfter(1, std::bind(&Printer::Print2, this));
  }

  void Print1() {
    std::lock_guard<std::mutex> guard(mutex_);
    if (num_ < total_) {
      num_++;
      printf("%s %d\n", __FUNCTION__, num_);
      loop_->RunAfter(1, std::bind(&Printer::Print1, this));
    } else {
      loop_->Quit();
    }
  }

  void Print2() {
    std::lock_guard<std::mutex> guard(mutex_);
    if (num_ < total_) {
      num_++;
      printf("%s %d\n", __FUNCTION__, num_);
      loop2_->RunAfter(1, std::bind(&Printer::Print2, this));
    } else {
      loop2_->Quit();
    }
  }

 private:
  net::EventLoop* loop_;
  net::EventLoop* loop2_;
  std::mutex mutex_;
  int num_;
  const int total_ = 10;
};

int main() {
  net::EventLoop loop;
  net::EventLoopThread loop_thread;
  net::EventLoop* loop2 = loop_thread.StartLoop();
  Printer printer(&loop, loop2);
  loop.Loop();
}